package com.yvon.maple.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.yvon.boot.common.result.ResponseData;
import com.yvon.boot.common.result.ResultCode;
import com.yvon.boot.jwt.utils.TokenUtil;
import com.yvon.maple.gateway.properties.IgnoreProperties;
import com.yvon.maple.pojo.LoginUser;
import io.netty.buffer.UnpooledByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static com.yvon.maple.constants.SystemConstant.Common.STR_LOGIN_USER;
import static com.yvon.maple.constants.SystemConstant.Common.TOKEN_HEADER;

/**
 * @author : Yvon
 * @since : 2022-03-16
 */
@Component
@Slf4j
public class TokenFilter implements WebFilter, Ordered {

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private IgnoreProperties ignoreProperties;



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();
        try {
            // 解码 并验证 token
            Mono<Void> token = parseToken(exchange, chain);
            if (token != null) {
                return token;
            }
        } catch (RuntimeException e) {
            return errorResponse(response, e.getMessage(), ResultCode.UNAUTHORIZED.getCode(), HttpStatus.UNAUTHORIZED);
        } catch (Exception e) {
            return errorResponse(response, "验证token出错", ResultCode.FAILED.getCode(), HttpStatus.BAD_REQUEST);
        }

        ServerHttpRequest build = mutate.build();
        return chain.filter(exchange.mutate().request(build).build());
    }

    @Override
    public int getOrder() {
        return -1000;
    }


    /**
     * 忽略 用户token
     */
    protected boolean isIgnoreToken(String path) {
        return ignoreProperties.isIgnoreToken(path);
    }

    private Mono<Void> parseToken(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();
        // 判断接口是否需要忽略token验证
        if (isIgnoreToken(request.getPath().toString())) {
            log.debug("当前接口：{}, 不解析用户token", request.getPath());
            return chain.filter(exchange);
        }

        // 获取请求头中的token
        String token = getHeader(TOKEN_HEADER, request);
        if (StrUtil.isEmpty(token)) {
            return errorResponse(response, ResultCode.TOKEN_NOT_FIND.getMessage(), ResultCode.TOKEN_NOT_FIND.getCode(), HttpStatus.UNAUTHORIZED);
        }
        LoginUser loginUser = tokenUtil.parseToken(token, LoginUser.class);

        // 将请求头中的token解析出来的用户信息重新封装到请求头，转发到业务服务
        // 业务服务在利用HeaderThreadLocalInterceptor拦截器将请求头中的用户信息解析到ThreadLocal中
        if (loginUser != null) {
            addHeader(mutate, STR_LOGIN_USER, JSONUtil.toJsonStr(loginUser));
        }

        return null;
    }

    protected String getHeader(String headerName, ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String token = StrUtil.EMPTY;
        if (headers.isEmpty()) {
            return token;
        }

        token = headers.getFirst(headerName);

        if (StrUtil.isNotBlank(token)) {
            return token;
        }

        return request.getQueryParams().getFirst(headerName);
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = URLUtil.encode(valueStr);
        mutate.header(name, valueEncode);
    }

    protected Mono<Void> errorResponse(ServerHttpResponse response, String errMsg, int errCode, HttpStatus httpStatus) {
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setStatusCode(httpStatus);
        NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
        String body = JSONUtil.toJsonStr(ResponseData.failed(errCode, errMsg));
        DataBuffer dataBuffer = nettyDataBufferFactory.wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }

}
